import datetime
from typing import List, Dict, Optional
from common.utils.utils_log import AntLogger
from views.template_page_view import FormItemDto
from das.setting_das import SettingDas, SettingModel


class DataDictionaryDasService:
    def __init__(self):
        # 使用SettingDas进行数据库操作
        self._setting_das = SettingDas()

    def save_or_update_common_setting(self, dict_key: str, dict_value: str, dict_desc: str = None):
        """
        保存或更新字典项
        如果键存在则更新，否则创建新条目
        """
        try:
            setting = self._setting_das.save_or_update_setting(dict_key, dict_value, dict_desc)
            AntLogger.info(f"字典项 {dict_key} 已保存: 值={dict_value}")
            return setting
        except Exception as e:
            AntLogger.error(f"保存字典项失败: {e}")
            raise

    def get_all_common_settings(self):
        """
        获取所有字典项及其值
        """
        try:
            # 从数据库获取所有设置
            settings = self._setting_das.get_all_settings()
            
            # 转换为FormItemDto列表
            form_items = []
            for setting in settings:
                form_items.append(
                    FormItemDto(
                        form_key=setting.setting_key,
                        form_desc=setting.setting_desc or setting.setting_key,
                        form_value=setting.setting_value or ""
                    )
                )
            
            # 如果没有设置，则生成默认表单项
            if not form_items:
                form_items = self._generate_default_form_items()
                
                # 保存默认表单项到数据库
                for item in form_items:
                    self.save_or_update_common_setting(
                        item.form_key, item.form_value, item.form_desc
                    )
            
            return form_items
        except Exception as e:
            AntLogger.error(f"获取所有设置失败: {e}")
            # 如果发生错误，返回默认表单项
            return self._generate_default_form_items()

    def get_setting_by_key(self, key: str) -> Optional[str]:
        """
        通过键获取特定设置值
        """
        try:
            setting = self._setting_das.get_setting_by_key(key)
            return setting.setting_value if setting else None
        except Exception as e:
            AntLogger.error(f"获取设置失败: {e}")
            return None

    def delete_setting(self, key: str) -> bool:
        """
        删除设置
        """
        try:
            return self._setting_das.delete_setting_by_key(key)
        except Exception as e:
            AntLogger.error(f"删除设置失败: {e}")
            return False

    def _generate_default_form_items(self) -> List[FormItemDto]:
        """
        生成默认表单项列表
        """
        # 默认表单项
        form_items = [
            FormItemDto(form_key="email_server",
                        form_desc="邮件服务器", form_value="smtp.example.com"),
            FormItemDto(form_key="email_port",
                        form_desc="邮件端口", form_value="587"),
            FormItemDto(form_key="max_retries",
                        form_desc="最大重试次数", form_value="3"),
            FormItemDto(form_key="timeout_seconds",
                        form_desc="超时时间(秒)", form_value="30"),
            FormItemDto(form_key="default_language",
                        form_desc="默认语言", form_value="zh_CN")
        ]
        return form_items
